package org.example.designPattern.structural.proxy.dynamicproxy.jdkProxy;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKProxy implements InvocationHandler {
    private IPerson person;

    /*
    * 对目标类进行增强
    * */
    public IPerson getInstance(IPerson person) {
        this.person = person;
        Class<? extends IPerson> clz = person.getClass();
        return (IPerson)Proxy.newProxyInstance(clz.getClassLoader(), clz.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 忽略 Object 自带方法（如 toString、hashCode）
        if (method.getDeclaringClass() == Object.class) {
            return method.invoke(person, args);
        }

        System.out.println("执行方法：" + method.getName());
        beforeProcess();
        Object invoke = method.invoke(this.person, args);
        afterProcess();
        return invoke;
    }

    private void beforeProcess(){
        System.out.println("欢迎来到非诚勿扰，说出你的要求：");
    }

    private void afterProcess(){
        System.out.println("配对成功开始交往");
    }
}
